﻿using System.Collections.Generic;
using System.Linq;
using Petshop.Backend.Data;
using Petshop.Backend.DTO;

namespace Petshop.Backend.Logic
{
    public class CatalogService
    {

        private readonly IDatabaseSession _databaseSession;

        public CatalogService()
            : this(new DatabaseSession())
        {
        }
        public CatalogService(IDatabaseSession databaseSession)
        {
            _databaseSession = databaseSession;
        }
        public CategoryInfo GetCategoryById(string categoryId)
        {
            if (string.IsNullOrEmpty(categoryId))
                return null;
            using (var rep = new CategoryRepository(_databaseSession))
            {
                var category = rep.FindById(categoryId);
                if (category != null)
                {
                    return Mapper.From(category);
                }
                else
                {
                    return null;
                }
            }
        }


        public List<ProductInfo> GetProductsByCategory(string categoryId)
        {
            if (string.IsNullOrEmpty(categoryId))
                return null;
            using (var rep = new ProductRepository(_databaseSession))
            {
                return rep.RetrieveProductByCategeoryId(categoryId).Select(product => Mapper.From(product)).ToList();
            }
           
        }


        public List<ProductInfo> GetProductsBySearch(string text)
        {
            if (string.IsNullOrEmpty(text))
                return null;
            using (var rep = new ProductRepository(_databaseSession))
            {
                return rep.FindProductBy(text).Select(product => Mapper.From(product)).ToList();
            }
        }


        public List<ItemInfo> GetItemsByProduct(string productId)
        {
            if (string.IsNullOrEmpty(productId))
                return null;
            using (var rep = new ItemRepository(_databaseSession))
            {
                return rep.RetrieveByProductId(productId).Select(item => Mapper.From(item)).ToList();
            }
        }


        public ItemInfo GetItemInfoById(string itemId)
        {
            if (string.IsNullOrEmpty(itemId))
                return null;
            using (var rep = new ItemRepository(_databaseSession))
            {
                var item =  rep.RetrieveById(itemId);
                if (item != null)
                {
                    return Mapper.From(item);
                }
                else
                {
                    return null;
                }
            }

        }
    }
}